# -*- coding: utf-8 -*-
import json
import logging
import threading
import time

import requests
from requests.exceptions import RequestException


class ApolloClient(object):
    def __init__(self, app_id, acs=None, cluster='default', config_server_url='http://localhost:8080', timeout=35):
        self.config_server_url = config_server_url
        self.appId = app_id
        self.cluster = cluster
        self.timeout = timeout
        self.stopped = False

        self._acs = acs
        self._stopping = False
        self._cache = {}
        self._cache_of_last_cipher = {}
        self._cache_of_last_plain = {}
        self._notification_map = {'application': -1}

    def get_boolean_value(self, key, default_val=None, namespace='application', auto_fetch_on_cache_miss=False):
        val = self.get_value(key=key, default_val=default_val, namespace=namespace,
                             auto_fetch_on_cache_miss=auto_fetch_on_cache_miss)
        return True if val == 'True' or val == 'true' or val == 'TRUE' or val == '1' or val is True else False

    def get_int_value(self, key, default_val=None, namespace='application', auto_fetch_on_cache_miss=False):
        val = self.get_value(key=key, default_val=default_val, namespace=namespace,
                             auto_fetch_on_cache_miss=auto_fetch_on_cache_miss)
        return int(val)

    def get_float_value(self, key, default_val=None, namespace='application', auto_fetch_on_cache_miss=False):
        val = self.get_value(key=key, default_val=default_val, namespace=namespace,
                             auto_fetch_on_cache_miss=auto_fetch_on_cache_miss)
        return float(val)

    # Main method
    def get_value(self, key, default_val=None, namespace='application', auto_fetch_on_cache_miss=False):
        if namespace not in self._notification_map:
            self._notification_map[namespace] = -1
            logging.getLogger(__name__).info("Add namespace '%s' to local notification map", namespace)

        if namespace not in self._cache_of_last_plain:
            self._cache_of_last_plain[namespace] = {}
            logging.getLogger(__name__).info("Add namespace '%s' to local cache", namespace)
            # This is a new namespace, need to do a blocking fetch to populate the local cache
            self._long_poll()

        if key in self._cache_of_last_plain[namespace]:
            return self._cache_of_last_plain[namespace][key]
        else:
            if auto_fetch_on_cache_miss:
                return self._cached_http_get(key, default_val, namespace)
            else:
                return default_val

    # Start the long polling loop. Two modes are provided:
    # 1: thread mode (default), create a worker thread to do the loop. Call self.stop() to quit the loop
    # 2: eventlet mode (recommended), no need to call the .stop() since it is async
    def start(self, use_eventlet=False):
        # First do a blocking long poll to populate the local cache, otherwise we may get racing problems
        if len(self._cache_of_last_plain) == 0:
            self._long_poll()

        if use_eventlet:
            import eventlet
            eventlet.spawn(self._listener)
        else:
            import signal
            signal.signal(signal.SIGINT, self._signal_handler)
            signal.signal(signal.SIGTERM, self._signal_handler)
            signal.signal(signal.SIGABRT, self._signal_handler)
            t = threading.Thread(target=self._listener)
            t.start()

    def stop(self):
        self._stopping = True
        logging.getLogger(__name__).info("Stopping listener...")

    def _cached_http_get(self, key, default_val, namespace='application'):
        url = '{}/configfiles/json/{}/{}/{}'.format(self.config_server_url, self.appId, self.cluster, namespace)
        r = requests.get(url)
        if r.ok:
            data = r.json()
            self._cache[namespace] = data
            self._decryptNS(namespace)
            logging.getLogger(__name__).info('Updated local cache for namespace %s', namespace)
        else:
            data = self._cache[namespace]

        if key in data:
            return data[key]
        else:
            return default_val

    def _uncached_http_get(self, namespace='application'):
        url = '{}/configs/{}/{}/{}'.format(self.config_server_url, self.appId, self.cluster, namespace)
        r = requests.get(url)
        if r.status_code == 200:
            data = r.json()
            self._cache[namespace] = data['configurations']
            self._decryptNS(namespace)
            logging.getLogger(__name__).info('Updated local cache for namespace %s release key %s: %s',
                                             namespace, data['releaseKey'],
                                             repr(self._cache_of_last_cipher[namespace]))

    def _decryptNS(self, namespace):
        update = {}
        cipher = self._cache_of_last_cipher.get(namespace)
        plain = self._cache_of_last_plain.get(namespace)
        if self._acs is not None:
            for (key, value) in self._cache[namespace].items():
                try:
                    if value.startswith('ENC(') and value.endswith(')'):
                        if cipher and value == cipher.get(key):
                            update[key] = plain[key]
                        else:
                            plaintext = self._acs.decrypt_blob(value[4:-1])
                            update[key] = plaintext
                            logging.getLogger(__name__).info('decrypt success.key(%s)', key)
                except Exception as ex:
                    logging.getLogger(__name__).error('decrypt failed(%s). key(%s)=value(%s)', ex, key, value)
        else:
            logging.getLogger(__name__).info('=====no available KMS Client=====')
        # 保存未解密的
        self._cache_of_last_cipher.update({namespace: dict(self._cache[namespace])})
        # 更新缓存
        self._cache[namespace].update(update)
        # 保存明文
        self._cache_of_last_plain.update({namespace: dict(self._cache[namespace])})

    def _signal_handler(self, signal, frame):
        logging.getLogger(__name__).info('You pressed Ctrl+C!')
        self._stopping = True

    def _long_poll(self):
        url = '{}/notifications/v2'.format(self.config_server_url)
        notifications = []
        for key in self._notification_map:
            notification_id = self._notification_map[key]
            notifications.append({
                'namespaceName': key,
                'notificationId': notification_id
            })

        try:
            r = requests.get(url=url, params={
                'appId': self.appId,
                'cluster': self.cluster,
                'notifications': json.dumps(notifications, ensure_ascii=False)
            }, timeout=self.timeout)
        except RequestException as e:
            logging.getLogger(__file__).warning('{}: {}'.format(e.__class__.__name__, str(e)))
            return

        # logging.getLogger(__name__).debug('Long polling returns %d: url=%s', r.status_code, r.request.url)

        if r.status_code == 304:
            # no change, loop
            # logging.getLogger(__name__).debug('No change, loop...')
            return

        if r.status_code == 200:
            data = r.json()
            for entry in data:
                ns = entry['namespaceName']
                nid = entry['notificationId']
                logging.getLogger(__name__).info("%s has changes: notificationId=%d", ns, nid)
                self._uncached_http_get(ns)
                self._notification_map[ns] = nid
        else:
            logging.getLogger(__name__).warning('Sleep...')
            time.sleep(self.timeout)

    def _listener(self):
        logging.getLogger(__name__).info('Entering listener loop...')
        while not self._stopping:
            self._long_poll()

        logging.getLogger(__name__).info("Listener stopped!")
        self.stopped = True


if __name__ == '__main__':
    import sys
    root = logging.getLogger()
    root.setLevel(logging.DEBUG)

    ch = logging.StreamHandler(sys.stdout)
    ch.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    root.addHandler(ch)
    client = ApolloClient('pycrawler', acs = None)
    client.start()
    if sys.version_info[0] < 3:
        v = raw_input('Press any key to quit...')
    else:
        v = input('Press any key to quit...')

    client.stop()
    while not client.stopped:
        pass
